package com.kai.auth.handler;

import com.kai.auth.enums.AuthErrorCodeConstants;
import com.kai.auth.util.LoginUserUtil;
import com.kai.common.data.Result;
import com.kai.common.util.IpAddressUtil;
import com.kai.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 权限处理器
 * </p>
 *
 * @author weijk
 * @since 2023/7/19
 */
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        String ip = IpAddressUtil.get(httpServletRequest);
        log.error("未授权, url=[{}], ip=[{}], uid:[{}], msg=[{}]", httpServletRequest.getRequestURI(), ip, LoginUserUtil.getUserId(), e.getMessage(), e);

        WebUtil.writeJson(Result.fail(AuthErrorCodeConstants.UNAUTHORIZED), httpServletResponse);
    }
}
